package cn.wit.test;
/*
 * 因为里面的线程都在等着加一，端住呢，但是外面的线程已经结束，所以count = 0，在调试的时候
 */

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DemoSynchorized {

	public static void main(String[] args) throws InterruptedException {

		// 线程同步
		Counter count = new Counter();

		//多个线程改同一个对象
		ExecutorService service = Executors.newFixedThreadPool(10);

		for (int i = 0; i < 10; i++) {
			//每个线程会把计数器加一
			service.execute(new CounterRunnable(count));
		}
		
		//因为get可能执行比里面线程快，可能线程卡在里面呢，还没出来，外面就已经调用呢getcount
		Thread.sleep(1000);
		
		System.out.println(count.getCount());
		
		service.shutdown();//关闭线程

	}

}

class CounterRunnable implements Runnable {

	private Counter c;

	public CounterRunnable(Counter c) {
		// TODO Auto-generated constructor stub
		this.c = c;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		c.count();
	}

}

class Counter {
	private int count = 0;

	public synchronized void count() {
		this.count = this.count + 1;
	}

	public synchronized int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}
}
